package com.shuqi.activity.adapter;

import com.shuqi.controller.R;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

/**
 * 搜索主页标签列表适配器
 * 
 * @author linyuren
 * 
 */
public class BookSearchLabellistAdapter extends BaseAdapter implements OnClickListener {

    /**
     * 包装内容的 adapter
     */
    private ListAdapter mAdapter = null;

    /**
     * 子item个数
     */
    private int mColumns = 1;

    /**
     * 监听器 onItemClickListener
     */
    private OnGridItemClickListener mGridListener;

    /**
     * The Context Object
     */
    private Context mContext;

    public BookSearchLabellistAdapter(Context context, ListAdapter adapter) {
        this.mContext = context;
        this.mAdapter = adapter;
    }

    public void setLabellistAdapter(ListAdapter adapter) {
        this.mAdapter = adapter;
    }

    @Override
    public void onClick(View v) {
        if (mGridListener == null) {
            // 如果监听器为空。。。
        } else {
            int pos = (Integer) v.getTag(R.id.search_labellist_content);
            int realPos = (Integer) v.getTag(R.id.search_labellist_item);
            mGridListener.onItemClick(pos, realPos);
        }
    }

    /** 设置事件监听器 */
    public void setOnItemClickListener(OnGridItemClickListener listener) {
        this.mGridListener = listener;
    }

    /** 设置每个item显示几个子item */
    public void setNumColumns(int columns) {
        this.mColumns = columns;
    }

    /** 获取子item个数 */
    public int getNumColumns() {
        return mColumns;
    }

    /** 接口方法 */
    public static interface OnGridItemClickListener {
        public void onItemClick(int pos, int realPos);
    }

    @Override
    public int getCount() {
        int count = (int) Math.ceil(mAdapter.getCount() / (double) mColumns);
        return count;
    }

    @Override
    public Object getItem(int position) {
        return mAdapter.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return mAdapter.getItemId(position);
    }

    @Override
    public boolean hasStableIds() {
        return mAdapter.hasStableIds();
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {
        mAdapter.registerDataSetObserver(observer);
    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {
        mAdapter.unregisterDataSetObserver(observer);
    }

    @Override
    public boolean areAllItemsEnabled() {
        return mAdapter.areAllItemsEnabled();
    }

    @Override
    public boolean isEnabled(int position) {
        return mAdapter.isEnabled(position);
    }

    @Override
    public int getItemViewType(int position) {
        return mAdapter.getItemViewType(position);
    }

    @Override
    public int getViewTypeCount() {
        return mAdapter.getViewTypeCount();
    }

    @Override
    public boolean isEmpty() {
        return mAdapter.isEmpty();
    }

    public ListAdapter getWrappedAdapter() {
        return mAdapter;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mColumns == 1) {
            View child = mAdapter.getView(position, convertView, parent);
            setOnItemClickListenerIfNeed(child, position, position);
            // no need
            return child;
        }
        return bindGridView(position, convertView, parent);
    }

    protected View bindGridView(int position, View convertView, ViewGroup parent) {
        ViewGroup root = null;
        if (convertView == null || !(convertView instanceof ViewGroup)) {
            root = createRoot();
            root.setClickable(false);
            root.setFocusable(false);
        } else {
            root = (ViewGroup) convertView;
        }
        return bindView(root, position);
    }

    /**
     * 为ListView创建item
     */
    protected ViewGroup createRoot() {
        LinearLayout root = new LinearLayout(mContext);
        root.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        root.setLayoutParams(lp);
        return root;
    }

    protected ViewGroup bindView(ViewGroup root, int pos) {
        final int count = mAdapter.getCount();
        final int childCount = root.getChildCount();

        for (int i = 0; i < mColumns; i++) {
            // real position
            int index = mColumns * pos + i;
            // 不足一行时，直接返回现有状态
            if (index == count) {
                // fix bug : root是有可能是系统缓存的root，这里直接返回root将导致如果此行数量
                // 不够columns，就会使用缓存的root里的child，为了避免这个问题，必须
                // 将缓存的child移除。
                removeCacheChild(root, index);
                break;
            } else if (index > count) {
                throw new UnknownError("unknowError");
            }

            View child = mAdapter.getView(index, root.getChildAt(i), root);
            setOnItemClickListenerIfNeed(child, pos, index);
            if (childCount == mColumns) {
                // root已经包含了Item，就没有必要继续添加了。
                continue;
            } else {
                if (i == 0 && childCount != 0) {
                    // 如果root已经包含item，但是并不全，这里就移除重新添加
                    root.removeAllViews();
                }
                LinearLayout.LayoutParams lp =
                        new LinearLayout.LayoutParams(
                                mContext.getResources().getDisplayMetrics().widthPixels / mColumns,
                                LinearLayout.LayoutParams.WRAP_CONTENT);
                child.setFocusable(true);
                child.setClickable(true);
                if (child instanceof ViewGroup) {
                    ((ViewGroup) child)
                            .setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
                }
                root.addView(child, lp);
            }
        }
        return root;
    }

    /**
     * remove child view in cache of root
     */
    private void removeCacheChild(ViewGroup root, int index) {
        int realColumns = (index - 1) % mColumns;
        int moveCount = (mColumns - 1) - realColumns;

        for (int i = 0; i < moveCount; i++) {
            final View child = root.getChildAt((mColumns - 1 - i));
            if (child != null) {
                root.removeView(child);
            }
        }
    }

    /**
     * 事件监听
     */
    private boolean setOnItemClickListenerIfNeed(View child, int pos, int realPos) {
        if (mGridListener == null) {
            return false;
        }
        child.setOnClickListener(this);
        child.setTag(R.id.search_labellist_content, pos);
        child.setTag(R.id.search_labellist_item, realPos);
        return true;
    }
}
